<?php
class AbstractDbObject
{
	// Db Object
	protected $dbConn = null;

	public function __construct($dbConn = null)
	{
		$this->dbConn = $dbConn;
	}

	/**
	 * Get Db Reader
	 *
	 * @return Zend_Db_Adapter_Abstract object
	 */
	public function getDbReader()
	{
		try
		{
			return !is_null($this->dbConn) ? $this->dbConn: Zend_Registry::get('dbReader');
		}
		catch (Exception $ex)
		{
			try
			{
				return $this->getDbWriter();
			}
			catch (Exception $ex)
			{
				throw new Exception($ex);
			}
		}
	}

	/**
	 * Get Db Writer
	 *
	 * @return Zend_Db_Adapter_Abstract object
	 */
	public function getDbWriter()
	{
		try
		{
			return !is_null($this->dbConn) ? $this->dbConn: Zend_Registry::get('dbWriter');
		}
		catch (Exception $ex)
		{
			throw new Exception($ex);
		}
	}

	/**
	 * Build where clause base on search criterias
	 *
	 * @param array $arrElement: array of search criterias
	 *
	 * @return string where clause
	 */
	public function buildWhereClause ($arrElement, $dbConn, $alias = '')
	{
		$query = '';

		if ( !is_null($arrElement) && is_array($arrElement) ) {
			$arr = array();
			foreach ($arrElement as $key => $value) {				
				if (is_int($key)) {
					// add direct where string
					$arr[] = $value;
				}
				else {
					$value = $dbConn->quote($value);
					if (empty($alias)){
						$arr[] = " ( $key=$value ) ";
					}else{
						$arr[] = " ( $alias.$key=$value ) ";
					}
				}

			}

			if (count($arrElement) > 0){
				$query .= " WHERE " . implode(' AND ', $arr);
			}

		}

		return $query;

	}

	/**
	 * Build Order By Clause
	 *
	 * @param string $orderBy: Field and the way ordered (ASC or DESC)
	 *
	 * @return string order by clause
	 */
	public function buildOrderClause ($orderBy) {
		$query = '';

		if( !is_null($orderBy) ) {
			$query .= " ORDER BY $orderBy ";

		}

		return $query;

	}

	/**
	 * Build Limit Clause
	 *
	 * @param int $begin: Begin item
	 * @param int $limit: Number rows to query
	 *
	 * @return string Limit Clause
	 */
	public function buildLimitClause ($begin, $limit) {
		$query = '';

		if(!is_null($begin) && !is_null($limit)){
			$query .=" LIMIT $begin, $limit ";

		}

		return $query;

	}

}